cmake_minimum_required(VERSION 3.28)
set(CMAKE_CXX_STANDARD 23)

project(boost_asio_tutorial)

# 设置 Boost 和 Protobuf 路径
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
    set(Boost_ROOT "C:/code_dependencies/boost")
    set(Protobuf_ROOT "C:/code_dependencies/protobuf")
    set(Protobuf_LIBRARY_DIR "C:/code_dependencies/protobuf/lib")
    set(nlohmann_json_ROOT "C:/code_dependencies/nlohmann_json")

    set(Protobuf_external_LIB_LIST
            ${Protobuf_LIBRARY_DIR}/abseil_dll.lib
    )
endif ()

set(Boost_NO_SYSTEM_PATHS ON) # 只搜索指定路径

find_package(Boost REQUIRED)
message(STATUS "Boost found: ${Boost_VERSION}.")

find_package(Protobuf REQUIRED)
message(STATUS "Protobuf found: ${Protobuf_VERSION}.")

find_package(nlohmann_json REQUIRED)
message(STATUS "nlohmann_json found: ${nlohmann_json_VERSION}.")

# 构建部分
file(GLOB CPP_FILES "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/*.h")
file(GLOB PROTO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/protos/*.proto")

file(GLOB MSG_NODE_CPP_FILES "${CMAKE_CURRENT_SOURCE_DIR}/MsgNode/*.cpp")
file(GLOB MSG_NODE_HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/MsgNode/*.h")

#message(STATUS "Found CPP files: ${CPP_FILES}")
#message(STATUS "Found HEADER files: ${HEADER_FILES}")
message(STATUS "Found PROTO files: ${PROTO_FILES}")

# 生成 .pb.cc 和 .pb.h 文件
message(STATUS "Generating protobuf sources...")
protobuf_generate_cpp(PROTO_GENERATED_SRCS PROTO_GENERATED_HDRS ${PROTO_FILES})
message(STATUS "Generated protobuf sources: ${PROTO_GENERATED_SRCS}")
message(STATUS "Generated protobuf headers: ${PROTO_GENERATED_HDRS}")

include_directories(${CMAKE_CURRENT_BINARY_DIR})

# 添加可执行文件和链接库
foreach (CPP_FILE ${CPP_FILES})
    get_filename_component(FILE_NAME ${CPP_FILE} NAME_WE)
    set(EXECUTABLE_NAME "${FILE_NAME}")

    #    set(HEADER_FILE "${CMAKE_CURRENT_SOURCE_DIR}/${FILE_NAME}.h")
    #    if (EXISTS ${HEADER_FILE})
    #        add_executable(${EXECUTABLE_NAME} ${CPP_FILE} ${HEADER_FILE} ${PROTO_GENERATED_SRCS})
    #    else ()
    #        add_executable(${EXECUTABLE_NAME} ${CPP_FILE} ${PROTO_GENERATED_SRCS})
    #    endif ()

    add_executable(${EXECUTABLE_NAME} ${CPP_FILE} ${PROTO_GENERATED_SRCS} ${MSG_NODE_CPP_FILES})
    message(STATUS "Creating executable: ${EXECUTABLE_NAME}")

    # 添加头文件的搜索路径
    target_include_directories(${EXECUTABLE_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})

    if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
        target_compile_definitions(${EXECUTABLE_NAME} PRIVATE _WIN32_WINNT=0x0A00)
    endif ()

    target_link_libraries(${EXECUTABLE_NAME}
            PUBLIC Boost::boost protobuf::libprotobuf ${Protobuf_external_LIB_LIST}
            PRIVATE nlohmann_json::nlohmann_json
    )
endforeach ()
